<template>
  <view class="page">
    <banner :position="12" height="320rpx"></banner>
    <!--搜索文章-->
    <view class="search-container">
      <image class="search-icon" :src="searchIcon"></image>
      <input type="text" v-model="searchContent" placeholder="搜索文章" class="input" @confirm="refreshList" />
    </view>

    <view class="filter-content">
      <!--			文章分类-->
      <view class="article-class-list">
        <view
          class="item"
          v-for="item in articleClassList"
          :key="item.id"
          :class="{ active: item.articlesClassId === currentSelectArticleClass }"
          @click="
            () => {
              currentSelectArticleClass = item.articlesClassId
              refreshList()
            }
          "
          >{{ item.articlesClassName }}</view
        >
      </view>
      <view class="filter-btn d-flex align-center justify-center" @click="() => $refs.datePicker.open()">筛选</view>
    </view>

    <view class="current-select-date-limit" v-if="!valIsEmpty(dateLimit.year) || !valIsEmpty(dateLimit.month)">
      <view>当前选择日期区间：</view>
      <view class="date">{{ dateLimit.year }}年</view>
      <view class="date" v-if="!valIsEmpty(dateLimit.month)">{{ dateLimit.month }}月</view>

      <view
        class="clear-btn"
        @click="
          () => {
            dateLimit = {
              year: '',
              month: '',
            }
            refreshList()
          }
        "
        >清空筛选</view
      >
    </view>

    <view class="article-wrapper">
      <!--			文章排序方式-->
      <view class="filter-header">
        <!--					背景底图-->
        <view class="bg"></view>
        <!--				选中左边-->
        <image :src="tabBgLeftIcon" mode="widthFix" class="active-bg" v-if="currentSelectArticleSortType === 'NEW'"></image>
        <!--				选中右边-->
        <image :src="tabBgRightIcon" mode="widthFix" class="active-bg" v-else-if="currentSelectArticleSortType === 'HOT'"></image>

        <view
          class="filter-item"
          v-for="item in articleSortTypeList"
          :key="item.value"
          :class="{ active: item.value === currentSelectArticleSortType }"
          @click="
            () => {
              currentSelectArticleSortType = item.value
              refreshList()
            }
          "
        >
          <!--					文字底图-->
          <image
            :src="item.textImage"
            mode="heightFix"
            class="text-image-icon"
            :style="{
              height: item.imageHeight,
              top: item.imageMarginTop,
            }"
          ></image>
        </view>
      </view>
      <!--			文章列表-->
      <view class="article-list">
        <template v-if="articleList.length > 0">
          <view class="article-item" v-for="item in articleList" :key="item.articlesId" @click="() => articleClick(item)">
            <!--					文章图标-->
            <image class="icon" :src="getShowImage(item.articlesIcon)"></image>
            <view class="right">
              <view class="header">
                <view class="left">
                  <!--						文章标题-->
                  <view class="article-title">{{ item.articlesTitle }}</view>
                  <!--						发布时间-->
                  <view class="publish-time">{{ item.publishTime }}</view>
                </view>
                <!--								收藏文章按钮-->
                <view class="collect-btn">
                  <!--									已经收藏-->
                  <image
                    class="icon"
                    v-if="!valIsEmpty(item.favoritesId)"
                    :src="collectedIcon"
                    @click.stop="handleCancelCollect(item)"
                  ></image>
                  <!--									还未收藏-->
                  <image class="icon" v-else :src="collectIcon" @click.stop="handleCollect(item)"></image>
                </view>
              </view>
              <view class="footer">
                <!--							文章阅读量-->
                <view class="reading-count">
                  <text class="number">{{ item.readingValue }}</text>
                  <text>人阅读</text>
                </view>
                <!--							文章标签列表-->
                <view class="article-class-name" v-for="label in item.articlesLabel" :key="label">{{ label }}</view>
              </view>
            </view>
          </view>
          <uni-load-more :status="loadMoreStatusText"></uni-load-more>
        </template>
        <!--				空状态-->
        <empty v-else height="820rpx"></empty>
      </view>
    </view>

    <datePicker
      ref="datePicker"
      @confirm="
        (obj) => {
          this.dateLimit = obj
          this.refreshList()
        }
      "
    ></datePicker>
  </view>
</template>

<script>
import banner from "@/components/banner.vue"
import searchIcon from "./assets/search.svg"
import request from "@/utils/request"
import uniLoadMore from "@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue"
import { getShowImage, handleUrlParams, showToast, valIsEmpty } from "@/utils"
import empty from "@/components/empty.vue"
import datePicker from "./components/datePicker.vue"
import collectedIcon from "./assets/collected.svg"
import collectIcon from "./assets/collect.svg"
import shareInfo from "@/utils/shareInfo"
import urlUtils from "@/utils/urlUtils"
import latestReleaseIcon from "./assets/latestRelease.png" // 最新发布文字底图
import byReadingCountIcon from "./assets/byReadingCount.png" // 按阅读量文字底图
import tabBgLeftIcon from "./assets/tab_bg_left.png" // tab左侧背景图
import tabBgRightIcon from "./assets/tab_bg_right.png" // tab右侧背景图

export default {
  data() {
    return {
      searchIcon,
      collectIcon,
      collectedIcon,
      searchContent: "", // 资讯文章搜索内容
      articleClassList: [], // 资讯文章分类列表
      currentSelectArticleClass: "all", // 当前选中的文章分类
      // 资讯文章排序类型列表
      articleSortTypeList: [
        {
          value: "NEW",
          label: "最新发布",
          textImage: latestReleaseIcon,
          imageHeight: "47.3rpx",
          imageMarginTop: "16rpx",
        },
        {
          value: "HOT",
          label: "按阅读量",
          textImage: byReadingCountIcon,
          imageHeight: "37.4rpx",
          imageMarginTop: "24rpx",
        },
      ],
      currentSelectArticleSortType: "NEW", // 当前选中的文章排序类型
      pagination: {
        current: 1,
        size: 10,
      },
      articleList: [],
      loadMoreStatusText: "more",
      dateLimit: {
        year: "",
        month: "",
      },
      tabBgLeftIcon,
      tabBgRightIcon,
    }
  },
  created() {
    //查校园热点子级下的所有文章分类
    request({
      url: "inforArticles/listTree",
      data: {
        articlesClassParentId: "17",
      },
      errorHandle: true,
      showLoading: true,
    }).then((data) => {
      this.articleClassList = [
        {
          articlesClassId: "all",
          articlesClassName: "全部",
        },
        {
          articlesClassId: "myFavorites",
          articlesClassName: "我的收藏",
        },
        ...data,
      ]
    })
    this.refreshList()
  },
  components: { banner, uniLoadMore, empty, datePicker },
  methods: {
    valIsEmpty,
    getShowImage,
    async getArticleList() {
      if (this.loadMoreStatusText === "loading") {
        return
      }
      this.loadMoreStatusText = "loading"
      // 处理文章分类id
      let articlesClassId
      // 如果是我的收藏或者全部，则取上级校园热点分类id
      if (["all", "myFavorites"].includes(this.currentSelectArticleClass)) {
        articlesClassId = "17" // 取上级校园热点分类id
      } else {
        articlesClassId = this.currentSelectArticleClass // 取当前选中的文章分类id
      }
      // 处理请求url
      let url
      // 如果是我的收藏，则请求我的收藏接口
      if (this.currentSelectArticleClass === "myFavorites") {
        url = "inforArticlesFavorites/getUserFavoritesByClient"
        // 如果是全部，则请求全部文章接口
      } else {
        url = "inforArticles/listArticlesV2"
      }
      const data = await request({
        url,
        data: {
          searchContent: this.searchContent,
          articlesClassId,
          sortType: this.currentSelectArticleSortType,
          ...this.pagination,
          ...this.dateLimit,
        },
        errorHandle: true,
      })
      // 处理标签列表
      for (let record of data.records) {
        record.articlesLabel = record.articlesLabel ? JSON.parse(record.articlesLabel) : []
      }
      this.articleList.push(...data.records)
      if (this.articleList.length >= data.total) {
        this.loadMoreStatusText = "noMore"
      } else {
        this.loadMoreStatusText = "more"
      }
    },
    refreshList() {
      this.pagination.current = 1
      this.articleList = []
      this.loadMoreStatusText = "more"
      uni.showLoading({ title: "加载中" })
      this.getArticleList().finally(() => {
        uni.hideLoading()
      })
    },
    // 	收藏文章
    handleCollect(item) {
      request({
        url: "inforArticlesFavorites/addFavorites",
        method: "post",
        data: {
          articlesId: item.articlesId,
          articlesClassId: item.articlesClassId,
        },
        errorHandle: true,
      }).then((data) => {
        this.$set(item, "favoritesId", data)
      })
    },
    // 取消收藏文章
    handleCancelCollect(item) {
      request({
        url: "inforArticlesFavorites/del",
        method: "post",
        data: {
          ids: [item.favoritesId],
        },
        errorHandle: true,
      }).then(() => {
        item.favoritesId = ""
      })
    },
    //资讯文章点击
    articleClick(item) {
      //获取资讯文章详情（统计阅读量）
      request({
        url: "inforArticles/getArticlesDetails",
        data: {
          articlesId: item.articlesId,
        },
        errorHandle: true,
        showLoading: true,
      }).then((data) => {
        //跳转到外部的地址
        if (item.linkType === "EXTERNAL") {
          uni.navigateTo({
            url: handleUrlParams("/pages/web-view/web-view", {
              path: encodeURIComponent(item.linkUrl),
            }),
          })
          //跳转到内部的详情页
        } else if (item.linkType === "NONE") {
          uni.navigateTo({
            url: handleUrlParams("/pages/examPreparationTips/detail", {
              articlesId: item.articlesId,
            }),
          })
        }
      })
    },
  },
  onReachBottom() {
    if (this.loadMoreStatusText === "noMore" || this.loadMoreStatusText === "loading") {
      return
    }
    this.pagination.current++
    this.getArticleList()
  },
  //右上角分享
  async onShareAppMessage() {
    return await shareInfo.getDefaultShareInfo({
      path: urlUtils.getCurrentPageUrl(),
    })
  },
}
</script>

<style scoped lang="scss">
.page {
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));

  > .search-container {
    margin: 0 auto;
    display: flex;
    align-items: center;
    width: 600rpx;
    height: 70rpx;
    border-radius: 35rpx;
    padding: 0 30rpx;
    box-shadow: 0 0 12rpx 2rpx rgba(0, 0, 0, 0.16);
    transform: translateY(-35rpx);
    background: white;

    > .search-icon {
      width: 34rpx;
      height: 34rpx;
    }

    > .input {
      width: 0;
      flex: 1;
      text-align: center;
    }
  }

  > .filter-content {
    padding: {
      left: 40rpx;
      right: 40rpx;
    }
    display: flex;
    > .article-class-list {
      width: 0;
      flex: 1;
      display: flex;
      overflow-x: auto;
      > .item {
        margin-right: 36rpx;
        font-size: 30rpx;
        position: relative;
        min-width: max-content;
        padding-bottom: 40rpx;
        &.active {
          color: #2cb980;
        }
        &.active::after {
          content: "";
          position: absolute;
          left: 0;
          bottom: 30rpx;
          height: 4rpx;
          background: #ffd658;
          width: 100%;
        }
      }
    }
    > .filter-btn {
      margin-left: 20rpx;
      width: 124rpx;
      height: 44rpx;
      font-size: 30rpx;
      background: #d7eee7;
      color: #2cb980;
      border-radius: 22rpx;
    }
  }

  > .current-select-date-limit {
    padding: 0 40rpx;
    font-size: 30rpx;
    margin-bottom: 30rpx;
    display: flex;
    > .date {
      color: #2cb980;
    }
    > .clear-btn {
      margin-left: 30rpx;
      color: var(--text-color-light);
      //文本加下划线
      text-decoration: underline;
    }
  }

  > .article-wrapper {
    border-radius: 30rpx;
    overflow: hidden;
    margin: 0 30rpx;
    box-shadow: 0 0 12rpx 2rpx rgba(0, 0, 0, 0.16);
    > .filter-header {
      display: flex;
      position: relative;
      height: 80rpx;
      > .bg {
        background: linear-gradient(to bottom, #8affcb, #d4ffc8);
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: calc(100% + 20rpx);
      }
      > .active-bg {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
      }
      > .filter-item {
        height: 100%;
        width: 0;
        flex: 1;
        font-size: 32rpx;
        font-weight: bold;
        position: relative;
        //&.active {
        //  background: linear-gradient(to bottom, #cfffe6, #fbfffd);
        //}
        > .text-image-icon {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
        }
      }
    }
    > .article-list {
      background: linear-gradient(to bottom, #ebfff4, white);
      padding: 0 30rpx;
      min-height: 820rpx;
      > .article-item {
        display: flex;
        padding: 30rpx 0;
        border-bottom: 2rpx solid #f0f0f0;
        > .icon {
          width: 140rpx;
          height: 140rpx;
        }
        > .right {
          width: 0;
          flex: 1;
          margin-left: 26rpx;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          > .header {
            display: flex;
            > .left {
              width: 0;
              flex: 1;
              > .article-title {
                font-size: 30rpx;
                //最多两行，溢出部分加省略号
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }
              > .publish-time {
                margin-top: 10rpx;
                font-size: 26rpx;
                color: var(--text-color-light);
              }
            }
            > .collect-btn {
              width: 40rpx;
              height: 40rpx;
              margin-left: 20rpx;
              > .icon {
                width: 100%;
                height: 100%;
              }
            }
          }
          > .footer {
            display: flex;
            font-size: 26rpx;
            > .reading-count {
              color: var(--text-color-light);
              > .number {
                color: #a77e00;
              }
            }
            > .article-class-name {
              margin-left: 30rpx;
              color: #4dc47c;
            }
          }
        }
      }
    }
  }
}
</style>
